import Vue from "vue";
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        taskList:[]
    },
    getters: {
        isAll(state,_this){
            return state.taskList.length>0 && state.taskList.length===_this.overNum;
        },
        overNum(state) {
            return state.taskList.reduce(function(sum, item) {
                if(item.isChecked) sum+=1;
                return sum;
            },0)
        }
    },
    mutations: {
        DEL_TASK_BY_ID(state, id){
            if(window.confirm("确认删除吗")){
                state.taskList=state.taskList.filter(v=>v.id !== id);
            }

        },
        //清除已完成任务
        CLEAR_OVER_TASK(state){
            state.taskList=state.taskList.filter(v=>!v.isChecked);
        },
        ALL_HANDLER(state){
            const isAll=!this.getters.isAll;
            state.taskList = state.taskList.map(function(item){
                item.isChecked=isAll;
                return item;
            })
        },
        UP_IS_CHECKED_BY_ID(state, id){
           state.taskList=state.taskList.map(item=>{
               if(item.id == id){
                   item.isChecked=!item.isChecked;
               }
               return item;
           })
            // console.log(state.taskList);
        },

        ADD_TASK_LIST (state, event) {
            const title=event.target.value.trim();
            console.log(event.target.value);
            if(!title) {
                alert("请输入");
                return;
            }
            if(state.taskList.some(v => v.title===title)) {
                alert("不允许重复");
                return;
            }
            state.taskList=[
                {
                    id:Math.random().toString(36),
                    title,
                    isChecked:true,
                },
                ...state.taskList
            ];
            event.target.value=null;

        }
    }
});
export default store;